﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.Text;
using System.Windows.Resources;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;

namespace SkyReader
{
    public partial class MainPage : PhoneApplicationPage
    {
        private string bookContent;
        private Book book = null;
        // Constructor

        //private bool isSavePageIndex = false;
        //private DateTime lastDateTime = DateTime.Now;

        public MainPage()
        {
            InitializeComponent();

            //In order to resolve the issue "saveing current page index", create a timer to save current page index
            
            //System.Windows.Threading.DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
            //dt.Interval = new TimeSpan(0, 0, 0, 0, 2000); // 10000 Milliseconds
            //dt.Tick += new EventHandler(dt_Tick);
            //dt.Start();


            this.TitlePanel.Visibility = System.Windows.Visibility.Collapsed;
            this.txtContent.Width = SystemConst.PAGE_WIDTH;
            this.txtContent.Height = SystemConst.PAGE_HIGHT;
            
            // 1. set backgroud color and font color
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains("SETTINGS_BACKGROUNDCOLOR"))
            {
                this.ContentPanel.Background = new SolidColorBrush(this.GetColor(settings["SETTINGS_BACKGROUNDCOLOR"].ToString()));
            }

            if (settings.Contains("SETTINGS_FONTCOLOR"))
            {
                this.txtContent.Foreground = new SolidColorBrush(this.GetColor(settings["SETTINGS_FONTCOLOR"].ToString()));
            }

            // 2. Get current book object;
            string fileName = settings["VARIABLE_CURRENTFILENAME"].ToString();

            
            foreach (var setting in settings)
            {
                if (setting.Value is Book)
                {
                    book = setting.Value as Book;
                    if (book.FileName == fileName)
                    {
                        break;
                    }
                }
            }

            this.txtContent.FontFamily =new FontFamily(book.FontFamily);
            this.txtContent.FontSize = book.FontSize;

            IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication();
            using (IsolatedStorageFileStream isoFs = new IsolatedStorageFileStream(fileName, FileMode.Open, isoFile))
            {
                Stream stream = isoFs;
                int length = (int)stream.Length;
                byte[] buffer = new byte[length];
                stream.Read(buffer, 0, length);

                System.Text.Encoding encoding = System.Text.Encoding.UTF8;

                bookContent = encoding.GetString(buffer, 0, length);
            }

            book.CurrentPage = book.CurrentPage - 1;
            this.NextPage();
        }

        //private void dt_Tick(object sender, EventArgs e)
        //{
        //    // Do Stuff here.
        //    if (isSavePageIndex == true && lastDateTime.AddSeconds(20) < DateTime.Now)
        //    {
        //        Deployment.Current.Dispatcher.BeginInvoke(SaveCurrentPageIndex);
        //        isSavePageIndex = false;
        //    }
        //}

        // Save current page index
        private void SaveCurrentPageIndex()
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            settings[book.Id] = this.book;
            settings.Save();
        }

        private void NextButton_Click(object sender, EventArgs e)
        {
            this.NextPage();
            
            //isSavePageIndex = true;
            //lastDateTime = DateTime.Now;
        }

        private void NextPage()
        {
            if (book.CurrentPage < this.book.PageDict.Count)
            {
                book.CurrentPage = book.CurrentPage + 1;

                if (book.CurrentPage == this.book.PageDict.Count)
                {
                    int currentPagePoint = this.book.PageDict[book.CurrentPage];
                    this.txtContent.Text = this.bookContent.Substring(currentPagePoint);
                }
                else
                {
                    int currentPagePoint = this.book.PageDict[book.CurrentPage];
                    int nextPagePoint = this.book.PageDict[book.CurrentPage + 1];
                    this.txtContent.Text = this.bookContent.Substring(currentPagePoint, nextPagePoint - currentPagePoint);
                }
            }
        }

        private void PrevButton_Click(object sender, EventArgs e)
        {
            this.PrevPage();
            
            //isSavePageIndex = true;
            //lastDateTime = DateTime.Now;
        }

        private void PrevPage()
        {
            if (book.CurrentPage>1)
            {
                book.CurrentPage = book.CurrentPage - 1;

                if (book.CurrentPage == this.book.PageDict.Count)
                {
                    int currentPagePoint = this.book.PageDict[book.CurrentPage];
                    this.txtContent.Text = this.bookContent.Substring(currentPagePoint);
                }
                else
                {
                    int currentPagePoint = this.book.PageDict[book.CurrentPage];
                    int nextPagePoint = this.book.PageDict[book.CurrentPage + 1];
                    this.txtContent.Text = this.bookContent.Substring(currentPagePoint, nextPagePoint - currentPagePoint);
                }
            }
        }

        private void settingsMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
        }

        private void bookmarksMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Bookmarks.xaml", UriKind.Relative));
        }

        private void setBookmarkMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SetBookmark.xaml", UriKind.Relative));
        }

        private void Homebutton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/RootPage.xaml", UriKind.Relative));
        }

        private void navigateMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Navigation.xaml", UriKind.Relative));
        }

        private Color GetColor(string colorName)
        {
            Color color = Colors.Black;
            switch (colorName)
            {
                case "Black":
                    color = Colors.Black;
                    break;
                case "Blue":
                    color = Colors.Blue;
                    break;
                case "Brown":
                    color = Colors.Brown;
                    break;
                case "Cyan":
                    color = Colors.Cyan;
                    break;
                case "DarkGray":
                    color = Colors.DarkGray;
                    break;
                case "Gray":
                    color = Colors.Gray;
                    break;
                case "Green":
                    color = Colors.Green;
                    break;
                case "LightGray":
                    color = Colors.LightGray;
                    break;
                case "Magenta":
                    color = Colors.Magenta;
                    break;
                case "Orange":
                    color = Colors.Orange;
                    break;

                case "Purple":
                    color = Colors.Purple;
                    break;
                case "Red":
                    color = Colors.Red;
                    break;
                case "White":
                    color = Colors.White;
                    break;
                case "Yellow":
                    color = Colors.Yellow;
                    break;
            }
            return color;
        }

        private void PhoneApplicationPage_Unloaded(object sender, RoutedEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(SaveCurrentPageIndex);
            //this.SaveCurrentPageIndex();
        }

      
    }


}